import React from 'react';
import PropTypes from 'prop-types'
// 防止xss攻击
import xss from 'xss';
import { withRouter } from 'react-router-dom';
import { observer, inject } from 'mobx-react';

// 公共组件
import Breadcrumbs from '../../components/breadcrumbs/index';
import RichEditor from '../../components/rich_editor/index';
// store
import User from '../../stores/user_store'
// 公共方法
import commFuc from '../../util/comm';
// request请求
import postArticle from '../../request/post_article';
import getArcDetail from '../../request/get_arc_detail';
import updateArticle from '../../request/update_article';
// 富文本组件
import './index.scss';

@inject((stores) => {
  const store = {
    user: stores.user,
  }
  return store
})
@observer
class PostArticleContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '',
      content: '',
      isEdit: this.props.urlParams.type === 'edit',
      editArticleId: '',
      editUserId: '',
      aditCategory: '',
    }
    this.onPost = this.onPost.bind(this)
    this.editorChange = this.editorChange.bind(this)
    this.titleChange = this.titleChange.bind(this)
  }
  componentDidMount() {
    this.onLoad()
  }
  componentDidUpdate(preProp) {
    if (preProp.urlParams !== this.props.urlParams) {
      this.switchType();
    }
  }
  onLoad() {
    this.getUserInfo();
    this.switchType()
  }
  // 提交文章
  onPost() {
    const params = {
      title: this.state.title,
      content: this.state.content,
      status: 'publish',

    };
    // 简单的字段验证

    for (const item in params) { // eslint-disable-line
      if (/(script)+/g.test(params[item])) {
        commFuc.errorTip('标题或者内容中有非法字符串,你不能输入script')
        return;
      }
      if (!params[item]) {
        commFuc.errorTip('标题或者内容为空');
        return;
      }
      params[item] = xss(params[item]);
    }
    // 编辑
    if (this.state.isEdit) {
      // 编辑提交需要的参数
      const editParam = Object.assign({}, params, {
        author: this.state.editUserId,
        categories: this.state.aditCategory,
      })
      const id = this.state.editArticleId
      updateArticle(id, editParam).then((res) => {
        if (res.status === 200 && res.data.id) {
          commFuc.successTip('文章发表成功...');
          this.props.history.push(`/article-detail/${res.data.id}`);
        } else {
          commFuc.errorTip(res.data.message)
        }
      }).catch(() => {
        alert(1)
        this.props.history.push(`/user/login/${encodeURIComponent(this.props.match.url)}`);
      })
    } else {
      // 发布
      postArticle(params).then((res) => {
        if (res.status === 200 && res.data.id) {
          commFuc.successTip('文章发表成功...');
          this.props.history.push(`/article-detail/${res.data.id}`);
        } else {
          commFuc.errorTip(res.data.message)
        }
      }).catch(() => {
        this.props.history.push(`/user/login/${encodeURIComponent(this.props.match.url)}`);
      })
    }
  }
  getUserInfo() {
    const { userInfo } = this.props.user;
    // 未登录跳转到登录界面
    if (!userInfo.user_id) {
      this.props.history.push(`/user/login/${encodeURIComponent(this.props.match.url)}`);
    }
  }
  // 选择是发布还是编辑
  switchType() {
    if (this.state.isEdit) {
      const { arcId } = this.props.urlParams;
      // 文章id存在是编辑
      if (arcId) {
        getArcDetail(arcId).then((res) => {
          // 文章不存在
          const json = res.data
          if (!json) {
            this.props.history.push('/404');
            return;
          }
          const { richEditor } = this.refs
          const data = json[0]
          if (-(0 - this.props.user.userInfo.user_id) !== -(0 - data.author)) {
            this.props.history.push(`/user/login/${encodeURIComponent(this.props.match.url)}`)
          }
          richEditor.setValue(data.content.rendered);
          this.setState({
            title: data.title.rendered,
            content: data.content.rendered,
            editArticleId: data.id,
            editUserId: data.author,
            aditCategory: data.categories[0],
          })
        })
      } else {
        // 文章id不存在是发布
        this.setState({
          title: '',
          content: '',
        })
        const { richEditor } = this.refs;
        richEditor.setValue('');
      }
    }
  }
  // 编辑框value改变
  editorChange(value) {
    this.setState({
      content: value,
    })
  }
  // 标题value改变
  titleChange(e) {
    this.setState({
      title: e.target.value,
    })
  }

  render() {
    return (
      <div id="post-article-container">
        <div className="w">
          <div className="container">
            <Breadcrumbs currentTitle="发布新文章" />
            {this.props.user.userInfo.user_id ?
              <div className="post-container">
                <input type="text" className="title" placeholder="请在此输入标题..." onChange={this.titleChange} value={this.state.title} />
                <RichEditor value={this.state.content ? this.state.content : '注意,不要使用中文输入法输入英文'} onChange={this.editorChange} title={this.state.title} ref="richEditor" />
                <button className="post-btn" onClick={this.onPost}>发表</button>
              </div> : ''
            }
          </div>
        </div>

      </div>
    )
  }
}
export default withRouter(PostArticleContainer);
PostArticleContainer.propTypes = {
  urlParams: PropTypes.objectOf(Object),
  history: PropTypes.objectOf(Object),
  user: PropTypes.instanceOf(User),
  match: PropTypes.objectOf(Object),
}
